<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>任务列表</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .header {
            background: #007AFF;
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            font-size: 24px;
            margin-bottom: 8px;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 14px;
        }
        
        .user-info {
            text-align: right;
        }
        
        .user-name {
            font-size: 16px;
            font-weight: 600;
        }
        
        .logout-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            margin-top: 8px;
        }
        
        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .content {
            padding: 30px;
        }
        
        .filter-section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .filter-group {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .filter-select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .search-input {
            flex: 1;
            min-width: 200px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .refresh-btn {
            background: #007AFF;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .refresh-btn:hover {
            background: #0056b3;
        }
        
        .task-list {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .task-item {
            border: 1px solid #e1e5e9;
            border-radius: 8px;
            padding: 20px;
            background: white;
            transition: all 0.3s;
        }
        
        .task-item:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        
        .task-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 15px;
        }
        
        .task-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        
        .task-category {
            display: inline-block;
            background: #007AFF;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        .task-status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-published {
            background: #d4edda;
            color: #155724;
        }
        
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .status-completed {
            background: #cce5ff;
            color: #004085;
        }
        
        .task-content {
            margin-bottom: 15px;
        }
        
        .task-description {
            color: #666;
            line-height: 1.5;
            margin-bottom: 10px;
        }
        
        .task-meta {
            display: flex;
            gap: 20px;
            font-size: 14px;
            color: #666;
            flex-wrap: wrap;
        }
        
        .meta-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .task-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }
        
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: #007AFF;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #007AFF;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }
        
        .empty-icon {
            font-size: 48px;
            margin-bottom: 20px;
        }
        
        .empty-text {
            font-size: 16px;
            margin-bottom: 20px;
        }
        
        .status-info {
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 8px;
            font-size: 14px;
            text-align: center;
        }
        
        .status-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .status-info.hidden {
            display: none;
        }
        
        .publish-task-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 50%;
            font-size: 24px;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            transition: all 0.3s;
        }
        
        .publish-task-btn:hover {
            background: #0056b3;
            transform: scale(1.1);
        }
        
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div>
                <h1>任务列表</h1>
                <p>查看可接取的无人机任务</p>
            </div>
            <div class="user-info">
                <div class="user-name" id="userName">飞手用户</div>
                <button class="logout-btn" onclick="logout()">退出登录</button>
            </div>
        </div>
        
        <div class="content">
            <!-- 筛选区域 -->
            <div class="filter-section">
                <div class="filter-group">
                    <select id="categoryFilter" class="filter-select">
                        <option value="">全部分类</option>
                    </select>
                    <select id="statusFilter" class="filter-select">
                        <option value="">全部状态</option>
                        <option value="1">已发布</option>
                        <option value="2">进行中</option>
                        <option value="3">已完成</option>
                    </select>
                    <input type="text" id="searchInput" class="search-input" placeholder="搜索任务...">
                    <button class="refresh-btn" onclick="loadTasks()">刷新</button>
                </div>
            </div>
            
            <!-- 状态信息 -->
            <div id="statusInfo" class="status-info hidden"></div>
            
            <!-- 任务列表 -->
            <div id="taskList" class="task-list">
                <!-- 任务项将通过JavaScript动态生成 -->
            </div>
            
            <!-- 空状态 -->
            <div id="emptyState" class="empty-state hidden">
                <div class="empty-icon">📋</div>
                <div class="empty-text">暂无任务</div>
                <div>当前没有可接取的任务</div>
            </div>
        </div>
    </div>
    
    <!-- 发布任务按钮（仅组织方可见） -->
    <button id="publishTaskBtn" class="publish-task-btn hidden" onclick="goToPublish()" title="发布任务">+</button>

    <script>
        let tasks = [];
        let categories = [];
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            if (checkLoginStatus()) {
                loadCategories();
                loadTasks();
                updateUserInfo();
            }
        });
        
        // 检查登录状态
        function checkLoginStatus() {
            const token = localStorage.getItem('token');
            const userType = localStorage.getItem('userType');
            
            if (!token) {
                showStatus('请先登录', 'error');
                setTimeout(() => {
                    window.location.href = '/login.html';
                }, 2000);
                return false;
            }
            
            // 如果是组织方，显示发布任务按钮
            if (userType === '2') {
                document.getElementById('publishTaskBtn').classList.remove('hidden');
            }
            
            return true;
        }
        
        // 更新用户信息
        function updateUserInfo() {
            const userType = localStorage.getItem('userType');
            const userName = userType === '2' ? '组织方用户' : '飞手用户';
            document.getElementById('userName').textContent = userName;
        }
        
        // 加载任务分类
        async function loadCategories() {
            try {
                const response = await fetch('/drone/taskSimple/categories');
                const result = await response.json();
                
                if (result.code === 200) {
                    categories = result.data;
                    updateCategoryFilter();
                }
            } catch (error) {
                console.error('加载分类失败:', error);
            }
        }
        
        // 更新分类筛选器
        function updateCategoryFilter() {
            const select = document.getElementById('categoryFilter');
            select.innerHTML = '<option value="">全部分类</option>';
            
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category.categoryId;
                option.textContent = category.categoryName;
                select.appendChild(option);
            });
        }
        
        // 加载任务列表
        async function loadTasks() {
            const token = localStorage.getItem('token');
            if (!token) {
                showStatus('请先登录', 'error');
                return;
            }
            
            try {
                const response = await fetch('/drone/task/list', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    tasks = result.rows || [];
                    renderTasks();
                } else {
                    showStatus('加载任务失败: ' + result.msg, 'error');
                }
            } catch (error) {
                showStatus('网络错误: ' + error.message, 'error');
            }
        }
        
        // 渲染任务列表
        function renderTasks() {
            const taskList = document.getElementById('taskList');
            const emptyState = document.getElementById('emptyState');
            
            if (tasks.length === 0) {
                taskList.innerHTML = '';
                emptyState.classList.remove('hidden');
                return;
            }
            
            emptyState.classList.add('hidden');
            
            const filteredTasks = getFilteredTasks();
            
            if (filteredTasks.length === 0) {
                taskList.innerHTML = '<div class="empty-state"><div class="empty-icon">🔍</div><div class="empty-text">没有找到匹配的任务</div></div>';
                return;
            }
            
            taskList.innerHTML = filteredTasks.map(task => `
                <div class="task-item">
                    <div class="task-header">
                        <div>
                            <div class="task-title">${task.taskTitle || '任务标题'}</div>
                            <span class="task-category">${getCategoryName(task.categoryId)}</span>
                        </div>
                        <span class="task-status ${getStatusClass(task.status)}">${getStatusText(task.status)}</span>
                    </div>
                    <div class="task-content">
                        <div class="task-description">${task.taskDescription || '暂无描述'}</div>
                        <div class="task-meta">
                            <div class="meta-item">
                                <span>📍</span>
                                <span>${task.location || '未指定地点'}</span>
                            </div>
                            <div class="meta-item">
                                <span>💰</span>
                                <span>¥${task.budgetMin || 0} - ¥${task.budgetMax || 0}</span>
                            </div>
                            <div class="meta-item">
                                <span>👥</span>
                                <span>最多${task.maxPilots || 1}人</span>
                            </div>
                            <div class="meta-item">
                                <span>📅</span>
                                <span>${formatDate(task.startTime)} - ${formatDate(task.endTime)}</span>
                            </div>
                        </div>
                    </div>
                    <div class="task-actions">
                        <button class="btn btn-secondary" onclick="viewTaskDetail(${task.taskId})">查看详情</button>
                        <button class="btn btn-primary" onclick="applyTask(${task.taskId})" ${task.status !== '1' ? 'disabled' : ''}>申请任务</button>
                    </div>
                </div>
            `).join('');
        }
        
        // 获取筛选后的任务
        function getFilteredTasks() {
            let filtered = [...tasks];
            
            const categoryFilter = document.getElementById('categoryFilter').value;
            const statusFilter = document.getElementById('statusFilter').value;
            const searchInput = document.getElementById('searchInput').value.toLowerCase();
            
            if (categoryFilter) {
                filtered = filtered.filter(task => task.categoryId == categoryFilter);
            }
            
            if (statusFilter) {
                filtered = filtered.filter(task => task.status === statusFilter);
            }
            
            if (searchInput) {
                filtered = filtered.filter(task => 
                    (task.taskTitle && task.taskTitle.toLowerCase().includes(searchInput)) ||
                    (task.taskDescription && task.taskDescription.toLowerCase().includes(searchInput)) ||
                    (task.location && task.location.toLowerCase().includes(searchInput))
                );
            }
            
            return filtered;
        }
        
        // 获取分类名称
        function getCategoryName(categoryId) {
            const category = categories.find(cat => cat.categoryId === categoryId);
            return category ? category.categoryName : '未知分类';
        }
        
        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                '0': '待审核',
                '1': '已发布',
                '2': '进行中',
                '3': '已完成',
                '4': '已取消',
                '5': '已拒绝'
            };
            return statusMap[status] || '未知状态';
        }
        
        // 获取状态样式类
        function getStatusClass(status) {
            const classMap = {
                '0': 'status-pending',
                '1': 'status-published',
                '2': 'status-published',
                '3': 'status-completed',
                '4': 'status-pending',
                '5': 'status-pending'
            };
            return classMap[status] || 'status-pending';
        }
        
        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未设置';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN');
        }
        
        // 查看任务详情
        function viewTaskDetail(taskId) {
            showStatus('查看任务详情功能开发中...', 'success');
        }
        
        // 申请任务
        function applyTask(taskId) {
            showStatus('申请任务功能开发中...', 'success');
        }
        
        // 跳转到发布任务页面
        function goToPublish() {
            window.location.href = '/task-publish.html';
        }
        
        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('userType');
            localStorage.removeItem('userId');
            window.location.href = '/login.html';
        }
        
        // 显示状态信息
        function showStatus(message, type) {
            const statusInfo = document.getElementById('statusInfo');
            statusInfo.textContent = message;
            statusInfo.className = `status-info status-${type}`;
            statusInfo.classList.remove('hidden');
            
            setTimeout(() => {
                hideStatus();
            }, 3000);
        }
        
        // 隐藏状态信息
        function hideStatus() {
            const statusInfo = document.getElementById('statusInfo');
            statusInfo.classList.add('hidden');
        }
        
        // 添加筛选器事件监听
        document.getElementById('categoryFilter').addEventListener('change', renderTasks);
        document.getElementById('statusFilter').addEventListener('change', renderTasks);
        document.getElementById('searchInput').addEventListener('input', renderTasks);
    </script>
</body>
</html>
